package com.holyn.guofang.view.distinguish;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseSectionQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.SectionEntity;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.ImageMergeWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.brand.BrandContract;
import com.holyn.guofang.presenter.brand.BrandPresenter;
import com.holyn.guofang.view.BaseActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/7/25.
 */

public class ImgPartitionPreviewActivity extends BaseActivity implements BaseView, BrandContract.ImgMergeView{
    private static final int REQUEST_ACTION_POST_IMG_MERGE = 0x0001;

    private static final String INTENT_KEY_SELECT_GROUP_NUM = "INTENT_KEY_SELECT_GROUP_NUM";
    private static final String INTENT_KEY_DEFAULT_SON_IMAGE_LIST = "INTENT_KEY_DEFAULT_SON_IMAGE_LIST";

    public static final String INTENT_KEY_SELECT_SON_IMAGE_LIST = "INTENT_KEY_SELECT_SON_IMAGE_LIST";

    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.btn_reset)
    Button btnReset;
    @BindView(R.id.btn_finish)
    Button btnFinish;

    private String SrcImgID;
    private String mainImageUrl;
    private String groupNum;
    private ArrayList<String> defaultSonImgLIst;

    private BrandContract.Presenter brandPresenter;
    private List<MySection> allDataList = new ArrayList<>();
    private List<MySection> showingDataList = new ArrayList<>();

    private SectionAdapter sectionAdapter;


    public static void startForResult(Activity fromActivity, String SrcImgID, String mainImageUrl, String groupNum, ArrayList<String> defaultSonImgLIst, int requestCode) {
        Intent intent = new Intent(fromActivity, ImgPartitionPreviewActivity.class);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID, SrcImgID);
        intent.putExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL, mainImageUrl);
        intent.putExtra(INTENT_KEY_SELECT_GROUP_NUM, groupNum);
        intent.putStringArrayListExtra(INTENT_KEY_DEFAULT_SON_IMAGE_LIST, defaultSonImgLIst);
        fromActivity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_img_parttion_preview;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("分拆预览");
        initData();

    }

    private void initData(){
        brandPresenter = new BrandPresenter(this);
        brandPresenter.addImgMergeView(this);

        SrcImgID = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_SRC_IMG_ID);
        mainImageUrl = getIntent().getStringExtra(SeniorDistinguishActivity.INTENT_KEY_MAIN_IMG_URL);
        groupNum = getIntent().getStringExtra(INTENT_KEY_SELECT_GROUP_NUM);
        defaultSonImgLIst = getIntent().getStringArrayListExtra(INTENT_KEY_DEFAULT_SON_IMAGE_LIST);

        brandPresenter.postImgMerge(REQUEST_ACTION_POST_IMG_MERGE, SrcImgID, groupNum);
    }

    @OnClick({R.id.btn_delete, R.id.btn_reset, R.id.btn_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_delete:
                Iterator<MySection> iterator = showingDataList.iterator();
                while (iterator.hasNext()){
                    MySection section = iterator.next();
                    if (section.getIsCheck() == true){
                        iterator.remove();
                    }
                }
                sectionAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_reset:
                for (MySection section: allDataList){
                    section.setIsCheck(false);
                }
                showingDataList.clear();
                showingDataList.addAll(allDataList);
                sectionAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_finish:
                ArrayList<String> selectSonImgUrlList = new ArrayList<>();
                for (MySection section: showingDataList){
                    if (section.getIsCheck() == true){
                        selectSonImgUrlList.add(section.t);
                    }
                }
                if (selectSonImgUrlList.size() == 0){
                    toastMsg("温馨提示 请选择组合子图");
                } else {
                    Intent intent = getIntent();
                    intent.putStringArrayListExtra(INTENT_KEY_SELECT_SON_IMAGE_LIST, selectSonImgUrlList);
                    setResult(Activity.RESULT_OK, intent);
                    ImgPartitionPreviewActivity.this.finish();
                }
                break;
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        closeLoadingDialog();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(int requestAction, ImageMergeWo imageMergeWo) {
        if (imageMergeWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<ImageMergeWo.DataBean.UrlBean> urlBeanList = imageMergeWo.getData().getUrl();
            allDataList.clear();
            allDataList.add(new MySection(true, mainImageUrl));
            for (String url: defaultSonImgLIst){
                allDataList.add(new MySection(url, false));
            }
            for (ImageMergeWo.DataBean.UrlBean urlBean: urlBeanList){
                allDataList.add(new MySection(urlBean.getImgUrl(), false));
            }

            showingDataList.clear();
            showingDataList.addAll(allDataList);

            sectionAdapter = new SectionAdapter(showingDataList);
            sectionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                    if (i >0){
                        showingDataList.get(i).setIsCheck(!showingDataList.get(i).getIsCheck());
                        sectionAdapter.notifyDataSetChanged();
                    }
                }
            });
            rvList.setLayoutManager(new GridLayoutManager(ImgPartitionPreviewActivity.this, 3));
            rvList.setAdapter(sectionAdapter);
        } else {
            toastMsg("获取数据失败");
            closeLoadingDialog();
        }
    }

    private class MySection extends SectionEntity<String>{

        private boolean isCheck = false;

        public MySection(boolean isHeader, String header) {
            super(isHeader, header);
        }

        public MySection(String url, boolean isCheck) {
            super(url);
            this.isCheck = isCheck;
        }

        public boolean getIsCheck() {
            return isCheck;
        }

        public void setIsCheck(boolean check) {
            isCheck = check;
        }
    }

    private class SectionAdapter extends BaseSectionQuickAdapter<MySection, BaseViewHolder> {

        public SectionAdapter(List<MySection> data) {
            super(R.layout.item_grid_img_partition_preview, R.layout.heard_img_partition_preview, data);
        }

        @Override
        protected void convertHead(BaseViewHolder baseViewHolder, MySection mySection) {
            ImageView ivMain = baseViewHolder.getView(R.id.iv_main);
            Glide.with(ImgPartitionPreviewActivity.this).load(mySection.header)
//                    .error(R.drawable.ic_empty_image)
                    .into(ivMain);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, MySection mySection) {
            baseViewHolder.setText(R.id.tv_group_index, "分拆组合"+baseViewHolder.getAdapterPosition()+"：");
            String sonUrl = mySection.t;
            ImageView ivSon = baseViewHolder.getView(R.id.iv_son);
            CheckBox cbSelect = baseViewHolder.getView(R.id.cb_select);
            Glide.with(ImgPartitionPreviewActivity.this).load(sonUrl)
//                    .error(R.drawable.ic_empty_image)
                    .into(ivSon);
            cbSelect.setChecked(mySection.getIsCheck());
        }
    }
}
